<?php

class User {
	private static $userTypes = array("user"=>1,"admin"=>2,"developer"=>3,"author"=>0,""=>0);
	public static function getCollection($person_id) {
		$collection = array();
		$users =DB::query('select * from `user` where `person`=\''.$person_id.'\'');
		return $users;
	}
	
	static function countReports(){
		if(!User::checkAccess('user'))die('Ошибка доступа!');
		$reps = Report::get("","",-1,"`author`='".$_SESSION['user']['person']['id']."'",'count(*) as length');
		if(isset($reps)&&$reps&&isset($reps[0])&&isset($reps[0]['length'])){
			return $reps[0]['length'];
		}else{
			return 0;
		}
	}

	public static function set($data,$id=-1,$flag=false) {
		$sql = "update `user` set ";
		$set = false;
		if($id<0){
			$id = $_SESSION['user']['id'];
		}else if(!$flag){
			if(!User::checkAccess('developer'))die('');
		}
		$comma = "";
		foreach ($data as $key => $value){
			if(!is_string($value)||$key=='password')continue;
			$val = trim($value);
			$sql.= $comma."`".$key."`='".$val."'";
			$comma=",";
			$set = true;
		}
		if($set)DB::exec_($sql." where `id`=".$id);
	}

	public static function get($login, $password, $db) {
		$u = false;
		$rows = DB::query("select * from user where login='" . $login . "' and password='" . $password . "'");
		if(count($rows) == 1) {
			$u 				= $rows[0];
			$u['person'] 	= Person::get($db,$u['person']);
		}
		return $u;
	}

	public static function getState() {
		if(!(isset($_SESSION['user'])&&isset($_SESSION['user']['id'])))return 0;
		if($_SESSION['user']['state']==1)return 1;
		$s = DB::query("select `state` from `user` where `id`='".$_SESSION['user']['id']."'");
		return $s[0]['state'];
	}
	
	static function checkAccess($access_type='user',$id=-1) {
		$userTypes 			= User::$userTypes;
		$u 					= isset($_SESSION['user'])?$_SESSION['user']:"";
		$user_type 			= $u!=""&&isset($u['type'])?$u['type']:'';
		$access_priority 	= isset($userTypes[$access_type])?$userTypes[$access_type]:-1;
		$user_priority 		= isset($userTypes[$user_type])?$userTypes[$user_type]:-1;
		if($id>=0&&isset($u)&&isset($u['person'])&&$id==$u['person']['id']){
			return true;
		}else if($id<0&&$user_priority>0&&$user_priority>=$access_priority){
			return true;
		}
		return false;
	}
	
	static function getViewData($db){
		$data 	= array("person_name"=>"","person_surname"=>"","reg_but_hide"=>"","tabs"=>"","tabs_buttons"=>"","user_nav"=>"","degree"=>"","state_class"=>"");
		$u 		= isset($_SESSION['user']) ? $_SESSION['user'] : false;
		$ajax 	= isset($_POST['ajax']) ? $_POST['ajax'] : false;
		$res 	= array();
		$admin 	= User::checkAccess('admin');
		if($u){
			$data['person_name'] 	= $u['person']['name'];
			$data['person_surname'] = $u['person']['surname'];
			$data['degree'] 		= $u['person']['degree'];
			$data['logo']			= $u['logo'];
			$res['html'] 			= Template::parse_("user/info", $data);
			$data['user_info'] 		= $res['html'];
			$data['reg_but_hide'] 	= "hide_";
		}else{			
			$data['user_info'] 		= Template::parse_('user/login');
			$res['html']			= $data['user_info'];
		}
		
		
		//Создание VIEW DATA для Гостя
		//
		$sp_data['admin_fields'] 	= "";
		if($admin){
			$sp_data['admin_fields'] = ",{name:'email',label:'Email'}";
		}
		$res['tabs']['main_page'] 	= array("html"=>Template::parse_('tabs/guest.main_page'),"lb"=>"Главная страница");
		$res['tabs']['section'] 	= array("html"=>Section::getViewData($db),"lb"=>"Конференция");
		$res['tabs']['persons'] 	= array("html"=>Template::parse_('person/list',$sp_data),"lb"=>"Участники");
		$res['tree'] 				= Section::getTree($db);
		$data['tree'] 				= $res['tree'];
		
		if($admin&&Conference::getState()==-1){
			$res['buttons']["Начать конференцию"]['opt'] 	= array("action"=>"load","target"=>"dialog","icon"=>"power");
			$res['buttons']["Начать конференцию"]['url'] 	= "start_conference";
		}
		
		if(!$ajax){
			$res['buttons']["Секции"]['opt']	= array("action"=>"load","target"=>"#tabs-id-section","icon"=>"folder-collapsed");
			$res['buttons']["Секции"]['url']	= "section/list_";
		}
		
		if(User::checkAccess('user')) {
			//Создания VIEW DATA которая доступна только зарегистрированным пользователям
			$res['buttons']["Мои доклады"]['opt'] 	= array("action"=>"load","target"=>"#tabs-id-section","icon"=>"note");
			$res['buttons']["Мои доклады"]['url'] 	= "report/getForAuthor";
			$res['buttons']["Мои сообщения"]['opt'] = array("disabled"=>true,"action"=>"load","target"=>"dialog","icon"=>"mail-closed","postData"=>array("form"=>true));
			$res['buttons']["Мои сообщения"]['url'] = "message/list_";
			if(Conference::getState()>0){
				$res['buttons']["Новый доклад"]['opt'] 	= array("action"=>"load","target"=>"dialog","icon"=>"plus","postData"=>array("form"=>true));
				$res['buttons']["Новый доклад"]['url'] 	= "report/new_";
			}
			$user_repots_length = User::countReports();
			if($user_repots_length<=0){
				$res['buttons']["Мои доклады"]['title'] = "У Вас нет докладов!";
				$res['buttons']["Мои доклады"]['opt']['disabled'] = "disabled";
			}
		}

		if($admin){
			$res['tabs']['tags'] 						= array("html"=>Tag::getViewData("","","grid"),"lb"=>"Ключевые слова");
			
			$res['buttons']["Новая секция"]['opt'] 		= array("action"=>"load","target"=>"dialog","icon"=>"circle-plus","postData"=>array("form"=>true));
			$res['buttons']["Новая секция"]['url'] 		= "section/new_";
			$res['buttons']["Новые доклады"]['opt'] 	= array("action"=>"load","target"=>"#tabs-id-section","icon"=>"note");
			$res['buttons']["Новые доклады"]['url'] 	= "report/newList";
		}
		
		if(User::checkAccess('developer')) {
			$res['tabs']['phpShell'] 						= array("html"=>Template::parse_("engine/php_shell"),"lb"=>"PHP Shell");
			$data['reg_but_hide'] 							= "";
			
			$res['buttons']["Удалённые доклады"]['opt'] 	= array("action"=>"load","target"=>"#tabs-id-section","icon"=>"note");
			$res['buttons']["Удалённые доклады"]['url'] 	= "report/removedList";
		}

		
		if($ajax){
			foreach($res['tabs'] as $key=>$t){
				$res['tabs']["tabs-id-".$key]['html'] 	= "<div class='p5 m5' id='tabs-id-ajax-".$key."'>".$t['html']."</div>";
				$res['tabs']["tabs-id-".$key]['lb'] 	= $t['lb'];
				unset($res['tabs'][$key]);
			}
			$res['reg_but_hide'] = $data['reg_but_hide'];
			return $res;
		}else if(isset($res['tabs'])){
			foreach ($res['tabs'] as $key=>$value) {
				$data['tabs'].="<div class='ui-widget-content ui-corner-all p5 m5' id='tabs-id-".$key."'>".$value['html']."</div>";
				$data['tabs_buttons'].='<li><a href="#tabs-id-'.$key.'" class="login_tab">'.$value['lb'].'</a></li>';
			}
			if(isset($res['buttons'])){
				foreach($res['buttons'] as $lb=>$but){
					$data['user_nav'].="<div class='m5'><a class='but login_but'".(isset($but['title'])?" title='".$but['title']."'":"")." data-url='".$but['url']."' data-opt='".json_encode($but['opt'])."'>".$lb."</a></div>";
					unset($res['buttons']);
				}
			}
		}

		return $data;
	}

	static function existsUser($login){
			$isExistsUser = DB::query("SELECT count(*) as length FROM `user` WHERE login='".$login."'");
			//print_r($isExistsUser);
			if(isset($isExistsUser[0])&&isset($isExistsUser[0]['length'])&&$isExistsUser[0]['length']==1){
				return true;
			}else{
				return false;
			}
	}
	
	static function validate($db) {
		$res['state'] = true;
		$res['error'] = array();
		$u = $_POST['user'];
		if(!isset($u)) { 				//если нет инфо по юзеру, стейт фолс, все плохо
			$res['state'] = false;
			return $res; 				//вернем рес с инфо об ошибке
		}
		// login check
		if(!(isset($u['login']) && (strlen($u['login']) < 20 && strlen($u['login']) >= 2) && !empty($u['login']))) {
			$res['state'] = false;
			$res['error']['user[login]'] = 1;
		} else {
			$isVacancedLogin = User::existsUser($u['login']);
			if($isVacancedLogin){
				$res['state'] = false;
				$res['error']['user[login]'] = 1;
			}
		}
		// passwords check
		if(!(isset($u['password']) && isset($u['password_repeat'])&&strlen($u['password'])==32&&strlen($u['password_repeat'])==32 && $u['password'] == $u['password_repeat'])) {
			$res['state'] = $res['state'] & true;
			$res['error']['user[password]'] = 1;
			$res['error']['user[password_repeat]'] = 1;
		}

		return $res;
	}

	static function create($data, $db) {
		$u = $_POST['user'];
		foreach($u as $key => $value) {
			$u[$key] = trim($value);
		}

		$state 		= '0';
		$type 		= 'user';
		$login 		= $u['login'];
		$pass 		= $u['password'];
		$person 	= $data['id'];

		try {
			$sql = "INSERT into `user` (`state`, `type`, `login`, `password`, `person`) VALUES ('$state', '$type', '$login', '$pass', '$person')";
			$dbres = $db -> exec($sql);
		} catch(PDOException $e) {
			$data['msg'] = "Error: " . $e -> errorInfo() . " sql: " . $sql;
			$data['state'] = false;
		}
		return $data;
	}

}
?>